package imwallet.dichen.com.library.http;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.text.ParseException;

import imwallet.dichen.com.library.utils.ToastUtils;
import imwallet.dichen.com.library.utils.Tools;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;

/**
 *
 * @author Administrator
 * @date 2018/7/10
 */

public abstract class RequestObservable<T> implements Observer<Response<T>> {
    private boolean mShowToast;

    public RequestObservable() {

    }

    public RequestObservable(boolean showMsg) {
        mShowToast = showMsg;
    }

    @Override
    public void onNext(@NonNull Response<T> tResponse) {
        if(tResponse.getCode() == Response.RESULT_OK) {
            onSuccess(tResponse.getResult());
        } else if(tResponse.getCode() == Response.CODE_NOLOGIN) {
            openLogin();
        } else {
            onFailed(tResponse.getCode(), tResponse.getMessage());
        }
    }

    private void openLogin() {
        // TODO 跳转到登录
        ToastUtils.showMessage("登录状态已过期~");
    }

    @Override
    final public void onError(@NonNull Throwable e) {
        String errorMsg;
        int errorCode;
        if (e instanceof JSONException || e instanceof ParseException) {
            errorMsg = "数据异常";
            errorCode = -1;
        } else if (e instanceof UnknownHostException) {
            errorMsg = "网络连接错误，请检查网络";
            errorCode = HttpCode.DNS_ERROR;
        } else if (!Tools.isNetworkAvailable() && e instanceof ConnectException) {
            errorMsg = "网络连接错误，请检查网络";
            errorCode = HttpCode.NETWORK_NOT_CONNECTED;
        } else {
            errorMsg = "服务器繁忙，请稍后重试";
            errorCode = HttpCode.UNKNOWN;
        }
        if(mShowToast) {
            ToastUtils.showMessage(errorMsg);
        }
        onFailed(errorCode, e.getMessage());
    }

    @Override
    final public void onComplete() {

    }

    /**
     * 请求成功的回调
     *
     * @param data
     */
    public abstract void onSuccess(T data);

    /**
     * 请求失败的回调
     *
     * @param code
     * @param msg
     */
    public abstract void onFailed(int code, String msg);
}
